from django.db import models

# Create your models here.
from django.db import models


class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)


class Customer(models.Model):
    name = models.CharField(max_length=100, db_index=True)  # 单字段索引
    email = models.EmailField()
    created_at = models.DateTimeField(auto_now_add=True)


class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    order_date = models.DateField()
    total_amount = models.DecimalField(max_digits=10, decimal_places=2)

    class Meta:
        indexes = [
            # 组合索引：客户 + 订单日期
            models.Index(fields=['customer', 'order_date']),

            # 带名称的组合索引
            models.Index(fields=['order_date', 'total_amount'], name='date_amount_idx')
        ]


from django.db.models.functions import Lower


class Product(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField()

    class Meta:
        indexes = [
            # 小写名称索引
            models.Index(Lower('name'), name='name_lower_idx'),

            # 带排序方向的函数索引
            models.Index(Lower('slug').desc(), name='slug_lower_desc_idx')
        ]


class UserProfile(models.Model):
    user = models.OneToOneField(Customer, on_delete=models.CASCADE)
    phone = models.CharField(max_length=20, unique=True)  # 唯一索引


class Task(models.Model):
    title = models.CharField(max_length=200)
    completed = models.BooleanField(default=False)
    due_date = models.DateField()

    class Meta:
        indexes = [
            # 只为未完成任务创建索引
            models.Index(
                fields=['due_date'],
                name='incomplete_due_date_idx',
                condition=models.Q(completed=False)
            )
        ]
